//
//  PictureView.swift
//  WBDemo
//
//  Created by Meng on 17/2/17.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit
import SDWebImage

class PictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, PhotoBrowserPresentationControllerDelegate {
    
    
    @IBOutlet weak var pictureCollectionViewHeightCons: NSLayoutConstraint!
    
    @IBOutlet weak var pictureCollectionViewWidthCons: NSLayoutConstraint!
    
    @IBOutlet weak var pictureFlowLayout: UICollectionViewFlowLayout!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        dataSource = self
        delegate = self
    }
    
    var viewModel: HomeViewModel? {
        didSet{
            // 更新pictureCell和collectionView的尺寸
            let (cellSize, collectionViewSize) = calculateSize()
            if cellSize != CGSize.zero {
                pictureFlowLayout.itemSize = cellSize
            }
            pictureCollectionViewWidthCons.constant = collectionViewSize.width
            pictureCollectionViewHeightCons.constant = collectionViewSize.height
            
            scrollsToTop = false
            reloadData()
        }
    }
    
    // MARK: - UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnail_urls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "pictureCell", for: indexPath) as! pictureCollectionViewCell
        if let url = viewModel?.thumbnail_urls?[indexPath.item] {
            
            cell.url = url
        }
        return cell
    }
    
    // MARK: - UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        // 获取当前点击图片的URL
        let url = viewModel!.bmiddle_urls![indexPath.item]
        
        // 取出被点击的cell
        let cell = collectionView.cellForItem(at: indexPath) as! pictureCollectionViewCell
        
        // 下载图片, 设置进度
        SDWebImageManager.shared().downloadImage(with: url, options: SDWebImageOptions.init(rawValue: 0), progress: { (current: Int, total: Int) in
            cell.pictureImageView.progress = CGFloat(current) / CGFloat(total)
        }) { (image: UIImage?, error: Error?, type: SDImageCacheType, b: Bool, url: URL?) in
            
            // 弹出一个控制器(图片浏览器), 告诉控制器哪些图片需要展示, 告诉控制器当前展示哪一张
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: ShowPhotoBrowserController), object: self, userInfo: ["bmiddle_urls": self.viewModel!.bmiddle_urls!, "indexPath": indexPath])
        }
    }
    
    // MARK: - 内部控制方法
    /// 计算cell和collectionview的尺寸
    private func calculateSize() -> (CGSize, CGSize) {
        /*
         没有配图: cell = zero, collectionview = zero
         一张配图: cell = image.size, collectionview = image.size
         四张配图: cell = {90, 90}, collectionview = {2*w+m, 2*h+m}
         其他张配图: cell = {90, 90}, collectionview =
         */
        let count = viewModel?.thumbnail_urls?.count ?? 0
        // 没有配图
        if count == 0 {
            return (CGSize.zero, CGSize.zero)
        }
        // 一张配图
        if count == 1 {
            if let key = viewModel?.thumbnail_urls?.first?.absoluteString {
                
                if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: key) {
                    
                    return (image.size, image.size)
                }
            }
            
        }
        
        // 四张配图
        let imageWidth: CGFloat = 90
        let imageHeight: CGFloat = 90
        let imageMargin: CGFloat = 10
        if count == 4
        {
            let col = 2
            let row = col
            // 宽度 = 图片的宽度 * 列数 + (列数 - 1) * 间隙
            let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
            // 宽度 = 图片的高度 * 行数 + (行数 - 1) * 间隙
            let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
            return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
        }
        
        // 其他张配图
        let col = 3
        let row = (count - 1) / 3 + 1
        // 宽度 = 图片的宽度 * 列数 + (列数 - 1) * 间隙
        let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
        // 宽度 = 图片的高度 * 行数 + (行数 - 1) * 间隙
        let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
        return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
    }
    
    // MARK: - PhotoBrowserPresentationControllerDelegate
    func browserPresentationWillShowImageView(browserPresenationController: PhotoBrowserPresentationController, indexPath: IndexPath) -> UIImageView? {
        let url = viewModel!.bmiddle_urls![indexPath.item]
        let imageView = UIImageView()
        imageView.sd_setImage(with: url)
        return imageView
    }
    func browserPresentationWillFromFrame(browserPresenationController: PhotoBrowserPresentationController, indexPath: IndexPath) -> CGRect {
        guard let cell = cellForItem(at: indexPath) as? pictureCollectionViewCell else {
            return CGRect.zero
        }
        
        let rect = convert(cell.frame, to: UIApplication.shared.keyWindow)
        return rect
    }
    func browserPresentationWillToFrame(browserPresenationController: PhotoBrowserPresentationController, indexPath: IndexPath) -> CGRect {
        guard let cell = cellForItem(at: indexPath) as? pictureCollectionViewCell else {
            return CGRect.zero
        }
        let width = UIScreen.main.bounds.width
        let height = UIScreen.main.bounds.height
        
        // 2.拿到被点击的图片
        let image = cell.pictureImageView.image!
        
        // 3.计算当前图片的宽高比
        let scale = image.size.height / image.size.width
        
        // 4.利用宽高比乘以屏幕宽度, 等比缩放图片
        let imageHeight = scale * width
        
        var offsetY: CGFloat = 0
        // 5.判断当前是长图还是短图
        if imageHeight < height
        {
            // 短图
            // 4.计算顶部和底部内边距
            offsetY = (height - imageHeight) * 0.5
        }
        return CGRect(x: 0, y: offsetY, width: width, height: imageHeight)
    }
}

class pictureCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var pictureImageView: ProgressImageView!
    
    @IBOutlet weak var gifImageView: UIImageView!
    
    var url: URL? {
        didSet {
            pictureImageView.sd_setImage(with: url)
            if let flag = url?.absoluteString.lowercased().hasSuffix("gif") {
                gifImageView.isHidden = !flag
            }
        }
    }
    
}
